import { existsSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
import { dirname, join, relative } from 'node:path/posix'
import { PROJECT_ROOT } from './utils/PROJECT_ROOT.ts'
import { ensureTsReferences } from './utils/ensureTsReferences.ts'
import { runCheckFix, runCommand } from './utils/runCommand.ts'
import { toPosixPath } from './utils/toPosixPath.ts'

const [pkgArg] = process.argv.slice(2).map((p) => toPosixPath(p))
if (!pkgArg) {
  console.error('Usage: pnpm packages:create <package-name>')
  process.exit(1)
}

const packageRoot = join(PROJECT_ROOT, 'packages', pkgArg)

if (existsSync(packageRoot)) {
  console.error(`❌ Package directory already exists: ${relative(PROJECT_ROOT, packageRoot)}`)
  process.exit(1)
}

// Generate package name from path
const generatePackageName = (pkgPath: string): string => {
  const segments = pkgPath.split('/')
  const pkgBasename = segments[segments.length - 1]

  // If nested (e.g., "ui/button"), use scoped name
  if (segments.length > 1) {
    const scope = segments.slice(0, -1).join('-')
    return `@lingma/${scope}__${pkgBasename}`
  }

  // Simple package name
  return `@lingma/${pkgBasename}`
}

const packageName = generatePackageName(pkgArg)

const FILES = {
  'package.json': {
    name: packageName,
    version: '0.0.1',
    type: 'module',
    main: './src/index.tsx',
    scripts: {
      lint: 'biome check .',
      'lint:fix': 'biome check --write .',
      format: 'biome format --write .',
    },
    dependencies: {
      react: 'catalog:',
    },
    devDependencies: {
      '@types/react': 'catalog:',
    },
  },
  'tsconfig.json': {
    extends: relative(packageRoot, join(PROJECT_ROOT, 'tsconfig.base.json')),
    include: ['./src'],
    compilerOptions: {
      outDir: './dist',
      rootDir: './src',
      tsBuildInfoFile: './tsconfig.tsbuildinfo',
    },
  },
  'src/index.tsx': `
    import { type ReactNode } from 'react';

    export const MyAwesomeComponent = (): ReactNode => {
      return <div>Hello, world!</div>
    }
`,
}

async function main() {
  console.log(`📦 Creating package: ${packageName}`)
  console.log(`📁 Location: ${relative(PROJECT_ROOT, packageRoot)}`)

  await mkdir(packageRoot, { recursive: true })

  console.log('📝 Creating files...')
  await Promise.all([
    ...Object.entries(FILES).map(async ([fileName, content]) => {
      const filePath = join(packageRoot, fileName)
      await mkdir(dirname(filePath), { recursive: true })
      await writeFile(
        filePath,
        typeof content === 'string' ? content : `${JSON.stringify(content, null, 2)}\n`,
        'utf8',
      )
      console.log(`  ✓ ${fileName}`)
    }),
  ])

  console.log('🔗 Updating TypeScript references...')
  ensureTsReferences({ fix: true })

  console.log('📥 Installing dependencies...')
  await runCommand('pnpm', ['install'], { cwd: PROJECT_ROOT })

  console.log('🔧 Running lint fix...')
  await runCheckFix()

  console.log(`\n✅ Package "${packageName}" created successfully!`)
  console.log(`\n📦 Package location: ${relative(PROJECT_ROOT, packageRoot)}`)
}

main().catch((error) => {
  console.error('❌ Error creating package:', error)
  process.exit(1)
})
